package edu.xidian.forum.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.xidian.forum.common.Result;
import edu.xidian.forum.dto.TipDto;
import edu.xidian.forum.entity.Tip;
import edu.xidian.forum.mapper.TipMapper;
import edu.xidian.forum.service.TipService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

@Service
public class TipServiceImpl extends ServiceImpl<TipMapper, Tip> implements TipService {
    @Override
    public Tip getRandomTip() {
        return baseMapper.getRandomTip();
    }

    @Override
    public Result<Tip> insertTip(TipDto tipDto) {
        if (tipDto.getContent() == null || tipDto.getAuthor() == null) {
            return Result.failed();
        }
        Tip tip = new Tip();
        tip.setContent(tipDto.getContent());
        tip.setAuthor(tipDto.getAuthor());
        try {
            baseMapper.insert(tip);
            return Result.success(tip);
        } catch (Exception e) {
            return Result.failed();
        }
    }

    @Override
    public Result<Tip> updateTip(TipDto tipDto) {
        if (tipDto.getId() == null || tipDto.getContent() == null || tipDto.getAuthor() == null) {
            return Result.failed();
        }
        Tip tip = new Tip();
        tip.setId(tipDto.getId());
        tip.setContent(tipDto.getContent());
        tip.setAuthor(tipDto.getAuthor());
        try {
            baseMapper.updateById(tip);
        } catch (Exception e) {
            return Result.failed();
        }
        return Result.success(tip);
    }

    @Override
    public Result<Void> deleteTip(TipDto tipDto) {
        if (tipDto.getId() == null) {
            return Result.failed();
        }
        Tip tip = new Tip();
        tip.setId(tipDto.getId());
        if (ObjectUtils.isEmpty(baseMapper.selectById(tip))) {
            return Result.failed("Repetitive Operation!");
        }
        try {
            baseMapper.deleteById(tip);
        } catch (Exception e) {
            return Result.failed();
        }
        return Result.success();
    }
}
